<?php

namespace Common\Model;

/**
 * @author ZXZ <zxz054321@163.com>
 */
class HooksModel {

    /**
     * 更新插件里的所有钩子对应的插件
     */
    public function updateHooks($addonName) {
        $addon_class = get_addon_class($addonName); //获取插件名

        if (!class_exists($addon_class)) {
            return false;
        }

        //获取有效钩子
        $methods = get_class_methods($addon_class);
        $hooks = M('Hooks')->getField('name', true);
        $common = array_intersect($hooks, $methods);

        if (!empty($common)) {
            foreach ($common as $hook) {
                $flag = $this->updateAddon($hook, $addonName);
                if (false === $flag) {
                    M('Hooks')->removeHooks($addonName);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 更新单个钩子处的插件
     */
    public function updateAddon($hook_name, $addon_name) {
        $hookId = M('Hooks')
                ->where("name='{$hook_name}'")
                ->getField('id', 1);

        $addonId = M('Addons')
                ->where("name='{$addon_name}'")
                ->getField('id', 1);

        //获取钩子对应的插件
        $o_addons = M('Listen')
                ->where("hook_id='{$hookId}'")
                ->getField('addon_id');

        if (!$o_addons) {
            $flag = M('Listen')->add(array(
                'hook_id' => $hookId,
                'addon_id' => $addonId
            ));
        }

        return $flag;
    }

}
